<?php

namespace app\admin\controller\item;

use app\admin\model;
use app\admin\model\ItemSku;
use app\common\controller\Backend;
use app\admin\model\inventory\Lists;
use app\admin\model\GoodsItem;
use app\admin\model\GoodsUnit;
use think\Db;
use think\Config;
use TCPDF;

use app\admin\model\Item as ItemProduct;


use app\admin\model\inventory\InventoryList as InventoryStorage;
use app\admin\model\Warehouse;
use app\admin\model\Logistics; //物流商
use app\admin\model\in\InInventory;
use app\admin\model\InventoryItemInfo;
use app\admin\model\in\InInventoryDetail;
use app\admin\model\out\OutInventoryAddr;
use app\admin\model\out\OutInventoryDetail;
use app\admin\model\inventory\InventoryDetail;
use app\admin\controller\warehouse\Inventorylist;
use app\admin\model\out\OutInventory;

class Item extends Backend {
  
    protected $model = null;
    protected $dataLimit = 'personal';
    protected $dataLimitField = 'uid';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Item;
        // $this->modelValidate = true;
    }

    public function index(){
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            
            //计算每个产品的库存数
            $InventoryStorageModel = new InventoryStorage();
            $goodsModel = new GoodsItem;

            foreach($list as $key=>$value){
              $goodsid = $goodsModel->where('code',$value['sku'])->value('id');
              $list[$key]['goods_count'] = intval($InventoryStorageModel->where('goods_id',$goodsid)->value('balance_count'));
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 校验用户的sku是否重复复
     *
     * @param [string] $userid
     * @param [string] $skuNo
     * @return bool
     */
    private function check_sku($userid,$skuNo){
      return false;
    }

    /**
     * 校验用户的条形码是否重复
     *
     * @param [type] $userid
     * @param [type] $barcode
     * @return bool
     */
    private function check_barcode($userid,$barcode){
      return false;
    }

    /**
     * 添加
     */
    public function add(){
      if ($this->request->isPost()) {
        $params = $this->request->post("row/a");
        if ($params) {
          if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->aid;
          }
          try {
            $validate = \think\Loader::validate('item');
            if(!$validate->scene('add')->check($params)){ 
                $this->error($validate->getError()); 
                die;
            }

            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                $this->model->validate($validate);
            }
            //事物开启
            Db::startTrans();
            
            $savedata = $params;
            unset($savedata['ProductUnit']);//因为在t_item表中没有ProductUnit字段
            $result = $this->model->allowField(true)->insertGetId($savedata);
            $id =  $this->model->getLastInsID();

            //同时插入goods表中商品  商品分类、商品编码、商品名称、计量单位(商品分类默认统一分类 CUSTOME_001)
         
            $goodsId = newId();
            $goodsItemModel = new \app\admin\model\GoodsItem();
            
            $goodsItemModel->id = $goodsId; //id
            $goodsItemModel->code = $params['sku']; 
            $goodsItemModel->name = $params['itemname'];
            $goodsItemModel->data_org = '#'; //产品全局对后台全局可看

            $goodsCategory = new \app\admin\model\GoodsCategory();
            $category = $goodsCategory->where('code',Config::get('category_code'))->find();

            $goodsItemModel->category_id = $category['id'];
            $goodsItemModel->bar_code = $params['barcode'];
            $goodsItemModel->original_sku = $params['sku'];

            $goodsItemModel->unit_id = $params['ProductUnit'];
            $goodsItemModel->item_id = $id;

            //获取当前用户的customeid 
            $userinfo = $this->auth->getUserInfo();
            $goodsItemModel->customer_id = $userinfo['customer_id'];
            $goodsItemModel->uuid = $userinfo['id'];
            $goodsItemModel->ushortid = $userinfo['aid'];
            $goodsItemModel->sale_price = $params['declareprice'];

            $goodsItemModel->save();
            // $sql = $goodsItemModel->getLastSql();
            // Db::commit();
            Db::commit();
            $this->success();

          } catch (\think\exception\PDOException $e) {
              $this->error($e->getMessage());
          } catch (\think\Exception $e) {
              $this->error($e->getMessage());
          }
        }
        $this->error(__('Parameter %s can not be empty', ''));
      }

      $productUnitModel = new GoodsUnit();
      $productUnits = $productUnitModel->where('1=1')->select();

      $productUnits = collection($productUnits)->toArray();
      $this->view->assign("productUnits", $productUnits);
      return $this->view->fetch();
    }

  /**
   * 产品的删除
   *
   * @param string $ids
   * @return void
   */
  public function del($ids = ""){
    if($this->request->isPost()){
      $condition=[];
      $itemModel = new \app\admin\model\Item();
      $goodsModel = new GoodsItem();
      $condition['id'] = $ids;
      $itemGoods = $itemModel->where($condition)->find();

      //事物开启
      Db::startTrans();

      try {
        $itemListModel = new Lists();
        $condition= [];
        $condition['uid'] = $itemGoods['uid'];
        $condition['sku'] = $itemGoods['sku'];
        $itemlist = $itemListModel->where($condition)->find();

        if($itemlist && $itemlist['inventorycount']>0){

          $this->error(sprintf('产品有库存数:%s，不允许删除',$itemlist['inventorycount']));
        }else{
          $itemGoods->delete(); //t_item中删除

          //查询t_goods表中对应的产品做删除 
          $condition= [];
          $condition['ushortid'] = $itemGoods['uid'];
          $condition['original_sku'] = $itemGoods['sku'];
          $goods = $goodsModel->where($condition)->find();
          $goods ? $goods->delete():''; //如果t_goods中有,则删除

          if($itemlist){
            $itemlist->delete();  //如果t_inventory_list库存一览表中存在的话，也删除
          }
          Db::commit();
          $this->success();
        }
      } catch (\think\Exception $e) {
        Db::rollback();
        $this->error($e->getMessage());
      }
    }
  }

   /**
   * 入库申请
   * @param null $ids
   * @return string
   */
  public function inWarehouse($ids = NULL){
    if ($this->request->isPost()) {
      $params = $this->request->post("row/a");
      if ($params) {
          try {
            //判断是否存在商品空数量
            foreach ($params['itemnum'] as $item){
              if($item<1){
                $this->error('请填写入库商品数量');
              }
            }
            Db::startTrans();
            $inData['boxcount'] = $params['boxcount'];
            $warehouseCode = $params['warehouse_code'];

            $warehouseModel = new Warehouse();
            $warehouseId = $warehouseModel->where(['code'=>$warehouseCode])->column('id')[0];

            $inData['warehouseid'] = $warehouseId;
            $inData['warehouse_code'] = $warehouseCode;
            $inData['remark'] = $params['remark'];
            $inorderid =  'IN'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
            $inData['inorderid'] =$inorderid;
            $inData[$this->dataLimitField] = $this->auth->aid;

            $inInventory = new InInventory();

            $result = $inInventory->save($inData);
            $inid = $inInventory->getLastInsID();
            if(!empty($inid) && $result !== false){
              //保存入库关联商品
              for($i=0;$i< count($params['itemid']);$i++){

                  //此处存储到详情表中
                  $inDetailModel = new InInventoryDetail;
                  $detailData = [];
                  $detailData['itemsku'] = $params['itemsku'][$i];
                  $detailData['itemid'] = $params['itemid'][$i];
                  $detailData['itemname'] = $params['itemname'][$i];
                  $detailData['goods_count'] = $params['itemnum'][$i];
                  $detailData['left_count'] = $params['itemnum'][$i];
                  $detailData['inid'] = $inid;
                  $detailData['id'] = newId();
                  $detailData['orderId'] = $inorderid;
                  $detailData['warehouseid'] = $warehouseId;
                  $detailData['warehouse_code'] = $warehouseCode;
                  $detailData['inBoxNo'] = $params['boxno'][$i];//入库的箱号
                  $rsDetail = $inDetailModel->save($detailData);

                  if( $rsDetail === false){
                      Db::rollback();
                      $this->error('入库申请失败，请重试');
                  }
              }
              Db::commit();
              $this->success();
            }else{
                $this->error('入库申请失败，请重试');
            }
          } catch (\think\exception\PDOException $e) {
              $this->error($e->getMessage());
          } catch (\think\Exception $e) {
              $this->error($e->getMessage());
          }
      }
      $this->error(__('Parameter %s can not be empty', ''));
    }

    // $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();

    $itemModel = new ItemProduct;

    $itemList = $itemModel->where('id','in',$ids)->select();

    //goods_id

    $items = collection($itemList)->toArray();
    $wms = $this->getWarehouse();


    $this->view->assign("items", $items);
    $this->view->assign("wms", $wms);
    return $this->view->fetch();
  }

  /*
  * 出库申请
  */
  public function outWarehouse($ids = NULL){
    if ($this->request->isPost()) {
      $params = $this->request->post("row/a");
      if ($params) {
        try {
          //判断是否存在商品空数量
          foreach ($params['itemnum'] as $item){
            if($item<1){
                $this->error('请填写出库商品数量');
            }
          }
          //查找商品对应库存数量 判断库存情况 进行提醒

          Db::startTrans();
          $inData['warehouse_code'] = $params['warehouse_code'];

          $mainId = newId();
          $warehouseModel = new Warehouse();
          $warehouseId = $warehouseModel->where(['code'=>$params['warehouse_code']])->column('id')[0];

          $inData['warehouseid'] = $warehouseId;
          $inData['file'] = $params['file'];
          $inData['remark'] = $params['remark'];
          $inData['orderid'] = $params['orderid'];
          $outOrderId = 'OUT'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
          $inData['outorderid'] = $outOrderId;
          $inData['uuid'] = $mainId;
          $inData[$this->dataLimitField] = $this->auth->aid;

          $inData['logistic_code'] = $params['logistic_code'];

          $outInventory = new OutInventory();
          $result = $outInventory->save($inData);

          $detailData = [];

          if($result !== false){
            //保存出库关联商品
            for($i=0;$i< count($params['itemid']);$i++){

                $data = [];
                $OutInventoryDetail = new OutInventoryDetail();

                $goodsModel = new GoodsItem();
                $goodId = $goodsModel->where('code',$params['itemsku'][$i])->value('id');
                
                //校验产品库存,库存不足的话，不允许出库申请
                $inventoryModel = new InventoryStorage();
                $balanceCount = $inventoryModel->where('goods_id',$goodId)->value('balance_count');//剩余库存

                if(intval($balanceCount)<intval($params['itemnum'][$i])){
                  $this->error(sprintf('产品SKU:%s,库存不足，请修改库存!',$params['itemsku'][$i]));
                  Db::rollback();
                  return false;
                  exit;
                }

                $data['id'] = \newId();
                $data['itemsku'] = $params['itemsku'][$i];
                $data['itemid'] = $params['itemid'][$i];
                $data['itemname'] = $params['itemname'][$i];

                $data['orderid'] = $params['orderid'];//关联的平台订单号

                $data['goods_count'] = $params['itemnum'][$i]; //申请出库数
                $data['sw_count'] = 0; //已出库数
                $data['left_count'] = $params['itemnum'][$i]; //未出库数

                $data['outid'] = $mainId;
                $data['out_orderno'] = $outOrderId;
                $data['warehouseid'] = $warehouseId;
                $data['warehouse_code'] = $params['warehouse_code'];

                // $data['recipients']= $params['recipients'];
                $data['first_name']= $params['firstName'];
                $data['last_name']= $params['lastName'];
                $data['mobile']= $params['mobile'];
                $data['company']= $params['company'];
                $data['state']= $params['state'];
                $data['province']= $params['province'];
                $data['city']= $params['city'];
                $data['postcode']= $params['postcode'];
                $data['addressone']= $params['addressone'];
                $data['addresstwo']= $params['addresstwo'];
                
                $rsDetail = $OutInventoryDetail->save($data);

                // $detailData[] = $data;
            }
            Db::commit();
            $this->success();
          }else{
            $this->error('出库申请失败，请重试');
          }
        } catch (\think\exception\PDOException $e) {
          $this->error($e->getMessage());
        } catch (\think\Exception $e) {
          $this->error($e->getMessage());
        }
      }
      $this->error(__('Parameter %s can not be empty', ''));
    }

        // $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
    $itemModel = new ItemProduct;
    $goodsModel = new GoodsItem;
    $itemList = $itemModel->where('id','in',$ids)->select();

    $items = collection($itemList)->toArray();
    $wms = $this->getWarehouse();
    $global = Config::get("global");

    $InventoryStorageModel = new InventoryStorage();
    foreach($items as $key=>$value){
      $goodsid = $goodsModel->where('code',$value['sku'])->value('id');
      $items[$key]['inventorycount'] = intval($InventoryStorageModel->where('goods_id',$goodsid)->value('balance_count'));
    }

    // $logisticsModel = Logistics();
    $logisticList = Logistics::all();
    $logisticList = collection($logisticList)->toArray();

  

    $this->view->assign("global",$global);
    $this->view->assign("items", $items);
    $this->view->assign("wms", $wms);
    $this->view->assign("logisticList", $logisticList);
    return $this->view->fetch();
  }

    //编辑时才 关联平台SKU
  public function edit($ids = NULL){
      $row = $this->model->get($ids);
      if (!$row)
        $this->error(__('No Results were found'));
      if ($this->request->isPost()) {
          $params = $this->request->post("row/a");
          
          if ($params) {

            $mapsku['id']  = ['<>',$ids];
            $mapsku['sku']  = ['=',$params['sku']];
            $itemList = Db('item')->where($mapsku)->select(); 
            // $sql = Db('item')->where($mapsku)->getLastSql();

            if(count($itemList)>0){
              $this->error('商品的sku相同!'); 
              die();
            }

            $mapbarcode['id']  = ['<>',$ids];
            $mapbarcode['barcode']  = ['=',$params['barcode']];
            $barCodeitemList = Db('item')->where($mapbarcode)->select(); 
            // $sql = Db('item')->where($mapbarcode)->getLastSql();

            if(count($barCodeitemList)>0){
              $this->error('商品的条形码相同!'); 
              die();
            }

            try {
                Db::startTrans();

                $savedata = $params;
                unset($savedata['ProductUnit']);//因为在t_item表中没有ProductUnit字段
                unset($savedata['rsku']);
                unset($savedata['name']);
                unset($savedata['itemsource']);
                // $result = $row->allowField(true)->save($savedata);

                $row->save($savedata,['id'=>$ids]);

                $itemSku = new ItemSku;
                $itemSku->where('itemid','=',$ids)->delete();

                if (isset($params['rsku'])) {
                    for ($i = 0; $i < count($params['rsku']); $i++) {
                        $data = array();
                        $data['sku'] = $params['rsku'][$i];
                        $data['name'] = $params['name'][$i];
                        $data['itemsource'] = $params['itemsource'][$i];
                        $data['isku'] = $row['sku'];
                        $data['itemid'] = $ids;

                        $rsItem = $itemSku->insert($data);
                        if ($rsItem === false) {
                            Db::rollback();
                            $this->error('保存失败，请重试');
                        }
                    }
                }


                //更新t_goods表中的信息
                $goodsItemModel = new \app\admin\model\GoodsItem(); 

                $savedata= [];
                $savedata['code'] = $params['sku']; 
                $savedata['name']  = $params['itemname'];
                $savedata['bar_code'] = $params['barcode'];
                $savedata['original_sku'] = $params['sku'];
                $savedata['unit_id'] = $params['ProductUnit'];
                $savedata['sale_price'] = $params['declareprice'];
                
                $goodsItemModel->save($savedata,['item_id' => $ids]);
                // $sql = $goodsItemModel->getLastSql();
                Db::commit();
                $this->success('修改成功！');
            } catch (\think\exception\PDOException $e) {
                $this->error($e->getMessage());
            } catch (\think\Exception $e) {
                $this->error($e->getMessage());
            }
          }
          $this->error(__('Parameter %s can not be empty', ''));
      }
      //取出关联SKU产品
      $itemSku = new ItemSku;
      $iSkus = $itemSku->where('itemid','=',$ids)->select();
      $itemSkus = collection($iSkus)->toArray();

      $productUnitModel = new GoodsUnit();
      $productUnits = $productUnitModel->where('1=1')->select();

      $productUnits = collection($productUnits)->toArray();
      $this->view->assign("productUnits", $productUnits);

      $this->view->assign("skus", $itemSkus);
      $this->view->assign("row", $row);
      return $this->view->fetch();
  }

  public function printItem(){
      $ids =  $this->request->get("ids");
      $info = $this->model->get($ids)->toArray();

      $this->toPdf($info);
  }

  public function toPdf($data){

      $pdf = new TCPDF(PDF_PAGE_ORIENTATION,PDF_UNIT, array(100,100), true, 'UTF-8', false);

      $pdf->SetCreator(PDF_CREATOR);
      $pdf->SetAuthor('Nicola Asuni');
      $pdf->SetTitle('TCPDF Example 002');
      $pdf->SetSubject('TCPDF Tutorial');
      $pdf->SetKeywords('TCPDF, PDF, example, test, guide');

      $pdf->setPrintHeader(false);
      $pdf->setPrintFooter(false);
      $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
      $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
      $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
      $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
      $pdf->SetFont('times', 'BI', 10);
      $pdf->AddPage();

      $style = array(
          'position' => '',
          'align' => 'C',
          'stretch' => false,
          'fitwidth' => true,
          'cellfitalign' => '',
          'border' => false,
          'hpadding' => 'auto',
          'vpadding' => 'auto',
          'fgcolor' => array(0,0,0),
          'bgcolor' => false,
          'text' => true,
          'font' => 'helvetica',
          'fontsize' => 8,
          'stretchtext' => 4
      );
      $style['position'] = 'C';
      $pdf->write1DBarcode($data['sku'], 'C128', '', '', '', 25, 0.4, $style, 'N');

      $pdf->SetFont('stsongstdlight', '', 8);
      $pdf->Write(0, $data['itemname'], '', 0, 'C', true, 0, false, false, 0);

      $Inbound = $data['sku'];

      $pdf->lastPage();
      $pdf->Output($Inbound.'.pdf', 'D');
  }

  /**
   * 导入产品
   */
  public function import(){
      $file = $this->request->request('file');
      if (!$file) {
          $this->error(__('Parameter %s can not be empty', 'file'));
      }
      $filePath = ROOT_PATH . DS . 'public' . DS . $file;
      if (!is_file($filePath)) {
          $this->error(__('No results were found'));
      }
      $PHPReader = new \PHPExcel_Reader_Excel2007();
      if (!$PHPReader->canRead($filePath)) {
          $PHPReader = new \PHPExcel_Reader_Excel5();
          if (!$PHPReader->canRead($filePath)) {
              $PHPReader = new \PHPExcel_Reader_CSV();
              if (!$PHPReader->canRead($filePath)) {
                  $this->error(__('Unknown data format'));
              }
          }
      }
      $PHPExcel = $PHPReader->load($filePath);
      $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
      $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
      $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
      $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);

      $itemProduct = new \app\admin\model\Item();
      
      try{
        Db::startTrans();
        for ($currentRow = 3; $currentRow <= $allRow; $currentRow++) {
          $sheetItem = [];
          for ($currentColumn = 0; $currentColumn < 17; $currentColumn++) {
              $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
              $sheetItem[] = is_null($val) ? '' : $val;
          }
         
          //保存商品信息

          
            
          // $inData['warehouseid'] = 1;
          $inData = [];
          $inData['itemname'] = $sheetItem[3];
          $inData['sku'] = $sheetItem[1];
          $inData['barcode'] = $sheetItem[2];
          $inData['source'] = $sheetItem[4];
          $inData['beforelong'] = $sheetItem[5];
          $inData['beforewidth'] = $sheetItem[6];
          $inData['beforehigh'] = $sheetItem[7];
          $inData['beforeweight'] = $sheetItem[8];
          $inData['afterlong'] = $sheetItem[9];
          $inData['afterwidth'] = $sheetItem[10];
          $inData['afterhigh'] = $sheetItem[11];
          $inData['afterweight'] = $sheetItem[12];
          $inData['describe'] = $sheetItem[14];
          $inData['customscode'] = $sheetItem[15];
          $inData['declareprice'] = $sheetItem[13];
          $inData['origincountry'] = $sheetItem[16];
          $inData[$this->dataLimitField] = $this->auth->aid;

          $validate = \think\Loader::validate('item');
          if(!$validate->scene('add')->check($inData)){ 
            $this->error($validate->getError()); 
            die;
          }

          $result = $this->model->allowField(true)->insertGetId($inData);
          $id =  $this->model->getLastInsID();

          //同时插入goods表中商品  商品分类、商品编码、商品名称、计量单位(商品分类默认统一分类 CUSTOME_001)
        
          $goodsId = newId();
          $goodsItemModel = new \app\admin\model\GoodsItem();
          
          $goodsItemModel->id = $goodsId; //id
          $goodsItemModel->code = $sheetItem[1];
          $goodsItemModel->name = $sheetItem[3];
          $goodsItemModel->data_org = '#'; //产品全局对后台全局可看

          $goodsCategory = new \app\admin\model\GoodsCategory();
          $category = $goodsCategory->where('code',Config::get('category_code'))->find();

          $goodsItemModel->category_id = $category['id'];
          $goodsItemModel->bar_code = $sheetItem[2];
          $goodsItemModel->original_sku = $sheetItem[1];

          $goodsItemModel->unit_id = '50C40382-B745-11E4-9C3C-782BCBD7746B';
          $goodsItemModel->item_id = $id;

          //获取当前用户的customeid 
          $userinfo = $this->auth->getUserInfo();
          $goodsItemModel->customer_id = $userinfo['customer_id'];
          $goodsItemModel->uuid = $userinfo['id'];
          $goodsItemModel->ushortid = $userinfo['aid'];
          $goodsItemModel->sale_price = $sheetItem[13];

          $goodsItemModel->save();
          // $sql = $goodsItemModel->getLastSql();
          // Db::commit();
          // Db::commit();

            
          // $itemProduct->save($inData);              
        }
        Db::commit();
        $this->success();
      } catch (\think\exception\PDOException $exception) {
          Db::rollback();
          $this->error($exception->getMessage());
      }

  }

  private function getWarehouse(){
    $wmsModel = model('Warehouse');
    $wms = $wmsModel->select();
    $wms = collection($wms)->toArray();
    return $wms;
  }


}
